package com.example.sea.model;

import android.content.Context;
import android.nfc.Tag;
import android.util.Log;

import com.example.sea.bean.Mail;
import com.example.sea.bean.MailItem;
import com.example.sea.bean.User;
import com.sun.mail.pop3.POP3Folder;
import com.sun.mail.pop3.POP3Message;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Properties;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.URLName;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;


public class TransmitMailImpl implements TransmitMail {

    private Context mContext;

    public TransmitMailImpl(Context context){
        mContext = context;
    }

    /**
     * 获得发件人的地址
     * @param message：Message
     * @return 发件人的地址
     */
    private String getFrom(Message message) throws Exception {
        InternetAddress[] address = (InternetAddress[]) ((MimeMessage) message).getFrom();
        String from = address[0].getAddress();
        if (from == null){
            from = "";
        }
        return from;
    }

    /**
     * 获得邮件主题
     * @param message：Message
     * @return 邮件主题
     */
    private String getSubject(Message message) throws Exception {
        String subject = "";
        if(((MimeMessage) message).getSubject() != null){
            subject = MimeUtility.decodeText(((MimeMessage) message).getSubject());// 将邮件主题解码
        }
        return subject;
    }

    /**
     * 获取邮件内容
     * @param part：Part
     */
    private String getMailContent(Part part) throws Exception {
        StringBuffer bodytext = new StringBuffer();//存放邮件内容
        //判断邮件类型,不同类型操作不同
        if (part.isMimeType("text/plain")) {
            bodytext.append((String) part.getContent());
        } else if (part.isMimeType("text/html")) {
            bodytext.append((String) part.getContent());
        } else if (part.isMimeType("multipart/*")) {
            Multipart multipart = (Multipart) part.getContent();
            int counts = multipart.getCount();
            for (int i = 0; i < counts; i++) {
                getMailContent(multipart.getBodyPart(i));
            }
        } else if (part.isMimeType("message/rfc822")) {
            getMailContent((Part) part.getContent());
        } else {}
        return bodytext.toString();
    }

    /**
     * 得到用户user的第id封邮件
     * @param user
     * @param id
     * @return
     */
    @Override
    public Mail getMail(User user, int id) {//public void receiveMail(String userName,String passWord)
        String userName = user.getUserName();
        String userPwd = user.getPassword();

        Mail mail = new Mail();
        ManageDaoImpl dao = new ManageDaoImpl(mContext);

        Store store = null;
        Folder folder = null;
        int messageCount = 0;
        URLName urln = null;

        try {
            //进行用户邮箱连接
            urln = new URLName("pop3", user.getPop3(), user.getPop3Port(), null,userName,userPwd);

            //获取session会话
            Properties properties = System.getProperties();
            properties.put("mail.smtp.host", user.getPop3());
            properties.put("mail.smtp.auth", "true");
            Session sessionMail = Session.getDefaultInstance(properties, null);

            store = sessionMail.getStore(urln);
            store.connect();

            //获得邮箱内的邮件夹Folder对象，以"只读"打开
            folder = store.getFolder("INBOX");//打开收件箱
            folder.open(Folder.READ_ONLY);//设置只读

            //处理邮件
            messageCount = folder.getMessageCount();// 获取所有邮件个数
            if(messageCount > 0) {
                Message[] messages = folder.getMessages(id, id);//读取第id封邮件
                for (int i = 0, n = messages.length; i < n; i++) {
                    String content = getMailContent((Part)messages[i]);//获取内容
                    POP3Folder inbox = (POP3Folder) folder;
                    String uid = inbox.getUID(messages[i]);
                    mail.setId(uid);
                    mail.setReceiver(userName);
                    mail.setSender(getFrom(messages[i]));//发送人
                    mail.setSubject(getSubject(messages[i]));
                    mail.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(((MimeMessage) messages[i]).getSentDate()));
                    mail.setContent(content);
                    ((POP3Message) messages[i]).invalidate(true);
                }
            }
        }catch(Exception e){
            e.printStackTrace();
            return null;
        }finally{
            if(folder != null && folder.isOpen()){
                try {
                    folder.close(true);
                } catch (MessagingException e) {
                    e.printStackTrace();
                }
            }
            if(store.isConnected()){
                try {
                    store.close();
                } catch (MessagingException e) {
                    e.printStackTrace();
                }
            }
        }
        return mail;
    }

    @Override
    public ArrayList<MailItem> getAllMail(User user) {
        ArrayList<MailItem> arrMails = new ArrayList<MailItem>();
        String userName = user.getUserName();
        String userPwd = user.getPassword();


        MailItem mi = new MailItem();
        ManageDaoImpl dao = new ManageDaoImpl(mContext);

        Store store = null;
        Folder folder = null;
        int messageCount = 0;
        URLName urln = null;

        try {
            //进行用户邮箱连接
                   System.out.print("\n"+userName+"-----"+userPwd+"\n");
            urln = new URLName("pop3", user.getPop3(), user.getPop3Port(), null, userName, userPwd);

            //获取session会话
            Properties properties = System.getProperties();

            properties.put("mail.smtp.host", user.getPop3());
            properties.put("mail.smtp.auth", "true");
            Session sessionMail = Session.getDefaultInstance(properties, null);

            store = sessionMail.getStore(urln);
            store.connect();

            //获得邮箱内的邮件夹Folder对象，以"只读"打开
            folder = store.getFolder("INBOX");//打开收件箱
            folder.open(Folder.READ_ONLY);//设置只读

            //处理邮件
            messageCount = folder.getMessageCount();// 获取所有邮件个数
            if(messageCount > 0) {
                Message[] messages = folder.getMessages(1, messageCount);//读取第id封邮件
                for(int i = 0; i < messageCount; i++) {
                    String content = getMailContent((Part)messages[i]);//获取内容
                    mi.setId(i+1);
                    mi.setSubject(getSubject(messages[i]));
                    mi.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(((MimeMessage) messages[i]).getSentDate()));
                    mi.setContentResume(content.substring(0,15)+"...");
                    mi.setRead(false);
                    ((POP3Message) messages[i]).invalidate(true);
                    arrMails.add(mi);
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            if(folder != null && folder.isOpen()){
                try {
                    folder.close(true);
                } catch (MessagingException e) {
                    e.printStackTrace();
                }
            }
            if(store!=null && store.isConnected()){
                try {
                    store.close();
                } catch (MessagingException e) {
                    e.printStackTrace();
                }
            }
        }
        return arrMails;
    }

    @Override
    public int sendMail(Mail mail) {                                                //返回错误代码没有
        //1、连接邮件服务器的参数配置
        Properties props = new Properties();//设置用户的认证方式
        props.setProperty("mail.smtp.auth", "true");//设置传输协议
        props.setProperty("mail.transport.protocol", "smtp");//设置发件人的SMTP服务器地址
        props.setProperty("mail.smtp.host", "smtp.test.com");//smtp.yeah.net

        //2、创建定义整个应用程序所需的环境信息的 Session 对象
        Session session = Session.getInstance(props);//设置调试信息在控制台打印出来
        session.setDebug(true);

        //3、创建邮件的实例对象
        MimeMessage msg = new MimeMessage(session);//创建一封邮件的实例对象
        ManageDaoImpl dao = new ManageDaoImpl(mContext);
        User user = dao.getUser(mail.getSender());
        try {
            msg.setFrom(new InternetAddress(mail.getSender()));//设置发件人地址
            /**
             * 设置收件人地址（可以增加多个收件人、抄送、密送），即下面这一行代码书写多行
             * MimeMessage.RecipientType.TO:发送
             * MimeMessage.RecipientType.CC：抄送
             * MimeMessage.RecipientType.BCC：密送
             */
            msg.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(mail.getReceiver()));//设置邮件主题
            msg.setSubject(mail.getSubject(), "UTF-8");//设置邮件正文
            msg.setContent(mail.getContent(), "text/html;charset=UTF-8");//设置邮件的发送时间,默认立即发送
            msg.setSentDate(new Date());

            //4、根据session对象获取邮件传输对象Transport
            Transport transport = session.getTransport();
            transport.connect(mail.getSender(), user.getPassword());//设置发件人的账户名和密码
            transport.sendMessage(msg, msg.getAllRecipients());//发送邮件，并发送到所有收件人地址，message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人

            //如果只想发送给指定的人，可以如下写法
            //transport.sendMessage(msg, new Address[]{new InternetAddress("xxx@qq.com")});

            //5、关闭邮件连接
            transport.close();
        }catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
        return 1;
    }

    public boolean isOKofSMTP(User user) {
        Properties props = new Properties();//设置用户的认证方式
        props.setProperty("mail.smtp.auth", "true");//设置传输协议
        props.setProperty("mail.transport.protocol", "smtp");//设置发件人的SMTP服务器地址
        props.setProperty("mail.smtp.host", "smtp.test.com");//smtp.yeah.net

        //2、创建定义整个应用程序所需的环境信息的 Session 对象
        Session session = Session.getInstance(props);//设置调试信息在控制台打印出来
        session.setDebug(true);

        //3、创建邮件的实例对象
        MimeMessage msg = new MimeMessage(session);//创建一封邮件的实例对象
        try {

            //4、根据session对象获取邮件传输对象Transport
            Transport transport = session.getTransport();
            transport.connect(user.getUserName(), user.getPassword());//设置发件人的账户名和密码
            transport.close();
        }catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public boolean isOKofPOP3(User user) {
        String userName = user.getUserName();
        String userPwd = user.getPassword();

        Mail mail = new Mail();

        Store store = null;
        Folder folder = null;
        int messageCount = 0;
        URLName urln = null;

        try {
            //进行用户邮箱连接
            urln = new URLName("pop3", user.getPop3(), user.getPop3Port(), null,userName,userPwd);
            //获取session会话
            Properties properties = System.getProperties();
            properties.put("mail.smtp.host", user.getPop3());
            properties.put("mail.smtp.auth", "true");
            Session sessionMail = Session.getDefaultInstance(properties, null);

            store = sessionMail.getStore(urln);
            store.connect();
            store.close();
        }catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
    /*public static void main(String[] args) {
        try {
            User u = new User();
            Mail m = new Mail();
            u.setUserName("daisy1z@yeah.net");
            u.setPassword("huqilin570*");
            //Context mContext = context;
            TransmitMail dao = new TransmitMailImpl();
            m = dao.getMail(u, 1);
            System.out.printf("Receiver"+m.getReceiver());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }*/

}
